import tkinter as tk
from tkinter import filedialog, messagebox
from PIL import Image, ImageTk
import os
import numpy as np
import image_channels
import image_io
import image_transform
import config
import sys
from image_utils import language_data, logging
import image_utils as utils
import subprocess


class ImageProcessor:
    def __init__(self, master):
        self.master = master
        self.current_language = language_data["current_language"]
        master.title(language_data[self.current_language]['app_title'])
        self.image = None
        self.original_image = None  # 新增：保存原始图像用于重置
        self.image_path = ""
        self.rect_start_x = None
        self.rect_start_y = None
        self.rect_end_x = None
        self.rect_end_y = None
        self.is_drawing = False
        self.current_rect = None
        self.mask = None  # 新增：用于存储掩模
        self.create_widgets()

    def create_widgets(self):
        menubar = tk.Menu(self.master)
        self.master.config(menu=menubar)

        file_menu = tk.Menu(menubar)
        file_menu.add_command(label=language_data[self.current_language]['open_original'], command=self.Open_as_original)
        file_menu.add_command(label=language_data[self.current_language]['open_grayscale'], command=self.Open_as_gray)
        file_menu.add_command(label=language_data[self.current_language]['merge_channels'], command=self.merge_channels)
        file_menu.add_command(label=language_data[self.current_language]['save_image'], command=self.save_image)
        file_menu.add_separator()

        language_menu = tk.Menu(file_menu)
        self.language_var = tk.StringVar(value=self.current_language)
        language_menu.add_radiobutton(label="中文", variable=self.language_var, value="zh", command=self.change_language)
        language_menu.add_radiobutton(label="English", variable=self.language_var, value="en", command=self.change_language)
        file_menu.add_cascade(label=language_data[self.current_language]['language'], menu=language_menu)

        file_menu.add_command(label=language_data[self.current_language]['exit'], command=self.master.quit)
        menubar.add_cascade(label=language_data[self.current_language]['file'], menu=file_menu)

        info_menu = tk.Menu(menubar)
        info_menu.add_command(label=language_data[self.current_language]['details'], command=self.show_image_details)
        menubar.add_cascade(label=language_data[self.current_language]['info'], menu=info_menu)

        edit_menu = tk.Menu(menubar)
        edit_menu.add_command(label=language_data[self.current_language]['crop'], command=self.crop_image)
        edit_menu.add_command(label=language_data[self.current_language]['reset'], command=self.reset_image)
        edit_menu.add_command(label="亮度调节", command=self.adjust_brightness)
        edit_menu.add_command(label="反色", command=self.invert_colors)  # 新增
        menubar.add_cascade(label=language_data[self.current_language]['edit'], menu=edit_menu)

        threshold_menu = tk.Menu(menubar)
        threshold_menu.add_command(label="全局阈值处理", command=self.global_threshold_processing)
        threshold_menu.add_command(label="Otsu阈值处理", command=self.otsu_threshold_processing)  # 新增
        menubar.add_cascade(label="阈值处理", menu=threshold_menu)

        edge_menu = tk.Menu(menubar)
        edge_menu.add_command(label="移动差分", command=self.move_difference)
        edge_menu.add_command(label="梯度算子(Sobel)", command=self.sobel_edge_detection)  # 新增
        menubar.add_cascade(label="边缘", menu=edge_menu)

        bitwise_menu = tk.Menu(menubar)
        create_mask_menu = tk.Menu(bitwise_menu)
        create_mask_menu.add_command(label="红色掩模", command=lambda: self.create_mask('red'))
        create_mask_menu.add_command(label="绿色掩模", command=lambda: self.create_mask('green'))
        create_mask_menu.add_command(label="蓝色掩模", command=lambda: self.create_mask('blue'))
        create_mask_menu.add_command(label="自定义颜色掩模", command=self.create_custom_mask)  # 新增
        bitwise_menu.add_cascade(label="创建掩模", menu=create_mask_menu)
        bitwise_menu.add_command(label="与运算(遮罩)", command=lambda: self.apply_mask('and'))
        bitwise_menu.add_command(label="或运算", command=lambda: self.apply_mask('or'))  # 新增
        bitwise_menu.add_command(label="非运算(反转)", command=lambda: self.apply_mask('not'))
        bitwise_menu.add_command(label="异或运算", command=lambda: self.apply_mask('xor'))  # 新增
        menubar.add_cascade(label="位运算", menu=bitwise_menu)

        split_menu = tk.Menu(menubar)
        menubar.add_cascade(label=language_data[self.current_language]['split'], menu=split_menu)
        split_menu.add_command(label=language_data[self.current_language]['split_channels'], command=self.split_image_channels)

        self.canvas = tk.Canvas(self.master, width=600, height=400)
        self.canvas.pack()
        self.canvas.bind("<Button-1>", self.on_mouse_down)
        self.canvas.bind("<B1-Motion>", self.on_mouse_move)
        self.canvas.bind("<ButtonRelease-1>", self.on_mouse_up)

    def change_language(self):
        self.current_language = self.language_var.get()
        utils.write_language_data(language_data, "current_language", self.current_language)
        logging.info(f"当前语言已切换为{self.current_language}。")
        confirm = messagebox.askyesno(language_data[self.current_language]['confirm_restart'],
                                      language_data[self.current_language]['restart_warning'])
        if confirm:
            self.master.destroy()
            subprocess.Popen([sys.executable] + sys.argv)

    def merge_channels(self):
        file_paths = filedialog.askopenfilenames()
        if not file_paths:
            return
        if len(file_paths) == 1:
            tk.messagebox.showerror(language_data[self.current_language]['error'],
                                    language_data[self.current_language]['single_file_error'])
            return
        try:
            self.image = image_channels.merge_image_channels(file_paths)
            self.original_image = self.image.copy()  # 保存原始图像
        except ValueError as e:
            tk.messagebox.showerror(language_data[self.current_language]['error'], str(e))
            return
        self.display_image()

    def split_image_channels(self):
        if self.image is None:
            tk.messagebox.showinfo(language_data[self.current_language]['error'],
                                   language_data[self.current_language]['no_image_loaded'])
            return
        if len(self.image.shape) == 2:
            tk.messagebox.showinfo(language_data[self.current_language]['error'],
                                   language_data[self.current_language]['single_channel_error'])
            return
        try:
            channels = image_channels.split_image_channels(self.image)
        except ValueError as e:
            tk.messagebox.showinfo(language_data[self.current_language]['error'], str(e))
            return
        for i, channel in enumerate(channels):
            window = tk.Toplevel(self.master)
            window.title(language_data[self.current_language]['channel_title'].format(i))
            canvas = tk.Canvas(window, width=300, height=300)
            canvas.pack()

            def save_channel(channel, index):
                save_path = filedialog.asksaveasfilename(defaultextension=config.DEFAULT_SAVE_FORMAT)
                if not save_path:
                    return
                image_io.save_image(channel, save_path)
                tk.messagebox.showinfo(language_data[self.current_language]['success'],
                                       language_data[self.current_language]['channel_saved'].format(index, save_path))

            save_button = tk.Button(window, text=language_data[self.current_language]['save_channel'],
                                    command=lambda channel=channel: save_channel(channel, i))
            save_button.pack()
            window.update()
            image = Image.fromarray(channel)
            canvas_width = canvas.winfo_width()
            canvas_height = canvas.winfo_height()
            image_width, image_height = image.size
            scale = min(canvas_width / image_width, canvas_height / image_height)
            if scale < 1:
                new_width = int(image_width * scale)
                new_height = int(image_height * scale)
                image = image.resize((new_width, new_height), Image.LANCZOS)
            else:
                new_width = int(image_width * scale)
                new_height = int(image_height * scale)
                image = image.resize((new_width, new_height), Image.BICUBIC)
            photo = ImageTk.PhotoImage(image)
            x = (canvas_width - new_width) // 2
            y = (canvas_height - new_height) // 2
            canvas.create_image(x, y, anchor=tk.NW, image=photo)
            canvas.image = photo
            title = f"Channel {i}"
            canvas.create_text(canvas_width // 2, 15, text=title, font=("Arial", 15), fill="black")
        logging.info("图像分割操作成功。")

    def show_image_details(self):
        if self.image is None:
            messagebox.showinfo(language_data[self.current_language]['error'],
                                language_data[self.current_language]['no_image_loaded'])
            logging.info("没有载入任何图像,无法显示图像细节。")
            return
        filename = os.path.basename(self.image_path)
        total_pixels = self.image.size
        shape = self.image.shape
        channels = shape[2] if len(shape) == 3 else 1
        dtype = self.image.dtype
        details = language_data[self.current_language]['info_str'].format(filename, total_pixels, shape, channels, dtype)
        messagebox.showinfo("INFO", details)
        logging.info("已显示图像细节。")

    def on_mouse_down(self, event):
        if self.current_rect and not self.is_drawing:
            self.canvas.delete(self.current_rect)
            self.current_rect = None
        else:
            self.rect_start_x = event.x
            self.rect_start_y = event.y
            self.is_drawing = True

    def on_mouse_move(self, event):
        if self.is_drawing:
            if self.current_rect:
                self.canvas.delete(self.current_rect)
            self.current_rect = self.canvas.create_rectangle(self.rect_start_x, self.rect_start_y, event.x, event.y,
                                                           outline="red")

    def on_mouse_up(self, event):
        self.rect_end_x, self.rect_end_y = event.x, event.y
        self.is_drawing = False
        self.crop_region = (min(self.rect_start_y, self.rect_end_y), max(self.rect_start_y, self.rect_end_y),
                            min(self.rect_start_x, self.rect_end_x), max(self.rect_start_x, self.rect_end_x))
        logging.info("已绘制裁剪区域。")

    def Open_as_original(self):
        logging.info("正在打开原始图像...")
        self.image_path = filedialog.askopenfilename()
        if not self.image_path:
            logging.info("没有选择任何图像文件,打开操作已取消。")
            return
        self.image = image_io.load_image(self.image_path)
        self.original_image = self.image.copy()  # 保存原始图像
        self.display_image()
        logging.info("成功打开原始图像。")

    def Open_as_gray(self):
        self.image_path = filedialog.askopenfilename()
        if not self.image_path:
            logging.info("没有选择任何图像文件,打开操作已取消。")
            return
        self.image = image_io.load_image(self.image_path, as_gray=True)
        self.original_image = self.image.copy()  # 保存原始图像
        self.display_image()
        logging.info("成功打开并转换为灰度图像。")

    def display_image(self):
        if self.image is None:
            logging.info("当前没有图像可显示。")
            return
        image = Image.fromarray(self.image)
        canvas_width = self.canvas.winfo_width()
        canvas_height = self.canvas.winfo_height()
        image_width, image_height = image.size
        scale = min(canvas_width / image_width, canvas_height / image_height)
        if scale < 1:
            new_width = int(image_width * scale)
            new_height = int(image_height * scale)
            image = image.resize((new_width, new_height), Image.LANCZOS)
        else:
            new_width = int(image_width * scale)
            new_height = int(image_height * scale)
            image = image.resize((new_width, new_height), Image.BICUBIC)
        photo = ImageTk.PhotoImage(image)
        self.canvas.delete("all")
        x = (canvas_width - new_width) // 2
        y = (canvas_height - new_height) // 2
        self.canvas.create_image(x, y, anchor=tk.NW, image=photo)
        self.canvas.image = photo
        logging.info("成功显示图像。")

    def save_image(self):
        if self.image is None:
            tk.messagebox.showinfo(language_data[self.current_language]['error'],
                                   language_data[self.current_language]['no_image_to_be_saved'])
            logging.error("没有图像可保存,保存操作已取消。")
            return
        save_path = filedialog.asksaveasfilename(defaultextension=config.DEFAULT_SAVE_FORMAT)
        if not save_path:
            logging.info("没有选择保存路径,保存操作已取消。")
            return
        image_io.save_image(self.image, save_path)
        logging.info(f"图像已成功保存到 {save_path}。")

    def crop_image(self):
        if self.image is None:
            tk.messagebox.showinfo(language_data[self.current_language]['error'],
                                   language_data[self.current_language]['no_image_to_be_cropped'])
            logging.error("没有图像可裁剪,裁剪操作已取消。")
            return
        if hasattr(self, 'crop_region') and self.current_rect:
            image_height, image_width = self.image.shape[:2]
            canvas_width = self.canvas.winfo_width()
            canvas_height = self.canvas.winfo_height()
            scale = min(canvas_width / image_width, canvas_height / image_height)
            offset_x = (canvas_width - image_width * scale) // 2
            offset_y = (canvas_height - image_height * scale) // 2
            real_crop_region = (
                int((self.crop_region[0] - offset_y) / scale),
                int((self.crop_region[1] - offset_y) / scale),
                int((self.crop_region[2] - offset_x) / scale),
                int((self.crop_region[3] - offset_x) / scale)
            )
            cropped_image = image_transform.crop_image(self.image, real_crop_region)
            if cropped_image is not None:
                self.image = cropped_image
                self.original_image = self.image.copy()  # 更新原始图像
                self.display_image()
                logging.info("图像裁剪成功。")
                self.canvas.delete(self.current_rect)
                self.current_rect = None
                del self.crop_region
            else:
                tk.messagebox.showinfo(language_data[self.current_language]['error'],
                                       language_data[self.current_language]['crop_failed'])
                logging.error("裁剪操作失败。")
        else:
            tk.messagebox.showinfo(language_data[self.current_language]['error'],
                                   language_data[self.current_language]['no_crop_area'])
            logging.error("没有选择裁剪区域,裁剪操作已取消。")

    def reset_image(self):
        if self.original_image is None:
            tk.messagebox.showinfo(language_data[self.current_language]['error'],
                                   language_data[self.current_language]['no_reset_image'])
            logging.error("没有图像可重置,重置操作已取消。")
            return
        self.image = self.original_image.copy()
        self.display_image()
        logging.info("图像已重置为原始状态。")

    # 亮度调节功能
    def adjust_brightness(self):
        if self.image is None:
            tk.messagebox.showinfo(language_data[self.current_language]['error'],
                                   language_data[self.current_language]['no_image_loaded'])
            return
        
        brightness_window = tk.Toplevel(self.master)
        brightness_window.title("亮度调节")
        brightness_window.geometry("300x150")
        
        # 创建亮度调节滑块
        brightness_var = tk.DoubleVar(value=1.0)
        brightness_scale = tk.Scale(brightness_window, from_=0.0, to=2.0, resolution=0.05,
                                   orient=tk.HORIZONTAL, label="亮度因子", length=250)
        brightness_scale.set(1.0)
        brightness_scale.pack(pady=10)
        
        # 原始图像备份用于实时预览
        original_img = self.image.copy()
        
        def update_preview():
            factor = brightness_scale.get()
            self.image = image_transform.adjust_brightness(original_img, factor)
            self.display_image()
        
        # 添加实时预览功能
        brightness_scale.bind("<Motion>", lambda e: update_preview())
        
        # 确认按钮
        confirm_button = tk.Button(brightness_window, text="确定", command=brightness_window.destroy)
        confirm_button.pack(pady=10)

    # 全局阈值处理功能
    def global_threshold_processing(self):
        if self.image is None:
            tk.messagebox.showinfo(language_data[self.current_language]['error'],
                                   language_data[self.current_language]['no_image_loaded'])
            return
        
        if len(self.image.shape) == 3:
            tk.messagebox.showinfo("提示", "请先将图像转换为灰度图")
            return
        
        threshold_window = tk.Toplevel(self.master)
        threshold_window.title("全局阈值处理")
        threshold_window.geometry("300x150")
        
        threshold_var = tk.IntVar(value=128)
        threshold_scale = tk.Scale(threshold_window, from_=0, to=255, orient=tk.HORIZONTAL,
                                  label="阈值", length=250)
        threshold_scale.set(128)
        threshold_scale.pack(pady=10)
        
        original_img = self.image.copy()
        
        def update_preview():
            threshold = threshold_scale.get()
            self.image = image_transform.global_threshold(original_img, threshold)
            self.display_image()
        
        threshold_scale.bind("<Motion>", lambda e: update_preview())
        
        confirm_button = tk.Button(threshold_window, text="确定", command=threshold_window.destroy)
        confirm_button.pack(pady=10)

    # 移动差分功能
    def move_difference(self):
        if self.image is None:
            tk.messagebox.showinfo(language_data[self.current_language]['error'],
                                   language_data[self.current_language]['no_image_loaded'])
            return
        
        if len(self.image.shape) == 3:
            tk.messagebox.showinfo("提示", "请先将图像转换为灰度图")
            return
        
        shift_window = tk.Toplevel(self.master)
        shift_window.title("移动差分")
        shift_window.geometry("300x150")
        
        shift_var = tk.IntVar(value=1)
        shift_scale = tk.Scale(shift_window, from_=1, to=10, orient=tk.HORIZONTAL,
                              label="位移量", length=250)
        shift_scale.set(1)
        shift_scale.pack(pady=10)
        
        original_img = self.image.copy()
        
        def update_preview():
            shift = shift_scale.get()
            self.image = image_transform.move_difference(original_img, shift)
            self.display_image()
        
        shift_scale.bind("<Motion>", lambda e: update_preview())
        
        confirm_button = tk.Button(shift_window, text="确定", command=shift_window.destroy)
        confirm_button.pack(pady=10)

    # 创建掩模功能
    def create_mask(self, color_channel):
        if self.image is None:
            tk.messagebox.showinfo(language_data[self.current_language]['error'],
                                   language_data[self.current_language]['no_image_loaded'])
            return
        
        if len(self.image.shape) != 3:
            tk.messagebox.showinfo("提示", "请使用彩色图像创建掩模")
            return
        
        self.mask = image_transform.create_channel_mask(self.image, color_channel)
        
        # 显示掩模
        mask_window = tk.Toplevel(self.master)
        mask_window.title(f"{color_channel}掩模")
        
        canvas = tk.Canvas(mask_window, width=300, height=300)
        canvas.pack()
        
        mask_image = Image.fromarray(self.mask * 255).convert("L")
        photo = ImageTk.PhotoImage(mask_image)
        canvas.create_image(0, 0, anchor=tk.NW, image=photo)
        canvas.image = photo
        
        logging.info(f"成功创建{color_channel}掩模")

    # 应用掩模功能
    def apply_mask(self, operation):
        if self.image is None:
            tk.messagebox.showinfo(language_data[self.current_language]['error'],
                                   language_data[self.current_language]['no_image_loaded'])
            return
        
        if self.mask is None:
            tk.messagebox.showinfo("提示", "请先创建掩模")
            return
        
        if len(self.image.shape) == 3 and len(self.mask.shape) == 2:
            # 扩展掩模维度以匹配彩色图像
            mask_3d = np.stack([self.mask] * 3, axis=-1)
        else:
            mask_3d = self.mask
        
        self.image = image_transform.apply_bitwise_operation(self.image, mask_3d, operation)
        self.display_image()
        logging.info(f"成功应用{operation}位运算")

    # 新增：反色功能
    def invert_colors(self):
        if self.image is None:
            tk.messagebox.showinfo(language_data[self.current_language]['error'],
                                   language_data[self.current_language]['no_image_loaded'])
            return
        self.image = image_transform.invert_colors(self.image)
        self.display_image()
        logging.info("图像反色处理成功")

    # 新增：Otsu阈值处理
    def otsu_threshold_processing(self):
        if self.image is None:
            tk.messagebox.showinfo(language_data[self.current_language]['error'],
                                   language_data[self.current_language]['no_image_loaded'])
            return
        
        if len(self.image.shape) == 3:
            tk.messagebox.showinfo("提示", "请先将图像转换为灰度图")
            return
        
        self.image = image_transform.otsu_threshold(self.image)
        self.display_image()
        logging.info("Otsu阈值处理成功")

    # 新增：Sobel边缘检测
    def sobel_edge_detection(self):
        if self.image is None:
            tk.messagebox.showinfo(language_data[self.current_language]['error'],
                                   language_data[self.current_language]['no_image_loaded'])
            return
        
        if len(self.image.shape) == 3:
            tk.messagebox.showinfo("提示", "请先将图像转换为灰度图")
            return
        
        self.image = image_transform.sobel_edge(self.image)
        self.display_image()
        logging.info("Sobel边缘检测成功")

    # 新增：自定义颜色掩模
    def create_custom_mask(self):
        if self.image is None:
            tk.messagebox.showinfo(language_data[self.current_language]['error'],
                                   language_data[self.current_language]['no_image_loaded'])
            return
        
        if len(self.image.shape) != 3:
            tk.messagebox.showinfo("提示", "请使用彩色图像创建掩模")
            return
        
        mask_window = tk.Toplevel(self.master)
        mask_window.title("自定义颜色掩模")
        mask_window.geometry("400x300")
        
        # 创建颜色范围选择滑块
        tk.Label(mask_window, text="颜色范围选择").grid(row=0, column=0, columnspan=2, pady=10)
        
        tk.Label(mask_window, text="Hue Min:").grid(row=1, column=0, sticky=tk.W, padx=10)
        hue_min = tk.Scale(mask_window, from_=0, to=180, orient=tk.HORIZONTAL, length=200)
        hue_min.set(0)
        hue_min.grid(row=1, column=1, padx=10)
        
        tk.Label(mask_window, text="Hue Max:").grid(row=2, column=0, sticky=tk.W, padx=10)
        hue_max = tk.Scale(mask_window, from_=0, to=180, orient=tk.HORIZONTAL, length=200)
        hue_max.set(180)
        hue_max.grid(row=2, column=1, padx=10)
        
        tk.Label(mask_window, text="Sat Min:").grid(row=3, column=0, sticky=tk.W, padx=10)
        sat_min = tk.Scale(mask_window, from_=0, to=255, orient=tk.HORIZONTAL, length=200)
        sat_min.set(0)
        sat_min.grid(row=3, column=1, padx=10)
        
        tk.Label(mask_window, text="Sat Max:").grid(row=4, column=0, sticky=tk.W, padx=10)
        sat_max = tk.Scale(mask_window, from_=0, to=255, orient=tk.HORIZONTAL, length=200)
        sat_max.set(255)
        sat_max.grid(row=4, column=1, padx=10)
        
        tk.Label(mask_window, text="Val Min:").grid(row=5, column=0, sticky=tk.W, padx=10)
        val_min = tk.Scale(mask_window, from_=0, to=255, orient=tk.HORIZONTAL, length=200)
        val_min.set(0)
        val_min.grid(row=5, column=1, padx=10)
        
        tk.Label(mask_window, text="Val Max:").grid(row=6, column=0, sticky=tk.W, padx=10)
        val_max = tk.Scale(mask_window, from_=0, to=255, orient=tk.HORIZONTAL, length=200)
        val_max.set(255)
        val_max.grid(row=6, column=1, padx=10)
        
        original_img = self.image.copy()
        
        def update_mask():
            h_min = hue_min.get()
            h_max = hue_max.get()
            s_min = sat_min.get()
            s_max = sat_max.get()
            v_min = val_min.get()
            v_max = val_max.get()
            
            lower = np.array([h_min, s_min, v_min])
            upper = np.array([h_max, s_max, v_max])
            
            self.mask = image_transform.create_custom_mask(original_img, lower, upper)
            
            # 更新预览
            preview_window = tk.Toplevel(self.master)
            preview_window.title("掩模预览")
            
            canvas = tk.Canvas(preview_window, width=300, height=300)
            canvas.pack()
            
            mask_image = Image.fromarray(self.mask * 255).convert("L")
            photo = ImageTk.PhotoImage(mask_image)
            canvas.create_image(0, 0, anchor=tk.NW, image=photo)
            canvas.image = photo
        
        create_button = tk.Button(mask_window, text="创建掩模", command=update_mask)
        create_button.grid(row=7, column=0, columnspan=2, pady=10)


def main():
    root = tk.Tk()
    app = ImageProcessor(root)
    root.mainloop()


if __name__ == "__main__":
    main()